<?php

namespace App\Jobs\System;
// 加载采集环境

use App\Wen\Utils\SiteUtils;
use Yansongda\Pay\Pay;
use App\Models\User\WxUser;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;

class CheckBatchCahceDataLossJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $flag = false;
            if(!Cache::has('app_share_format')){
                $flag = true;
                $app_share_format = [
                    'app_share_right' => Settings::get('app_share_right'),
                    'app_share_user' => Settings::get('app_share_user'),
                    'app_share_author' => Settings::get('app_share_author'),
                    'app_share_shop' => Settings::get('app_share_shop'),
                    'app_share_circle' => Settings::get('app_share_circle'),
                    'app_share_tag' => Settings::get('app_share_tag'),
                    'app_share_good' => Settings::get('app_share_good'),
                    'app_share_search' => Settings::get('app_share_search'),
                    'app_share_post' => Settings::get('app_share_post'),
                ];
                Cache::put('app_share_format', json_encode($app_share_format));
            }

            if(!Cache::has('app_page_animation')){
                $flag = true;
                $animation = [
                    "animation_1" => Settings::get('app_page_animation_1'),
                    "animation_2" => Settings::get('app_page_animation_2'),
                    "animation_3" => Settings::get('app_page_animation_3'),
                    "animation_4" => Settings::get('app_page_animation_4'),
                    "animation_5" => Settings::get('app_page_animation_5'),
                    "animation_6" => Settings::get('app_page_animation_6'),
                    "animation_7" => Settings::get('app_page_animation_7'),
                    "animation_8" => Settings::get('app_page_animation_8'),
                    "animation_10" => Settings::get('app_page_animation_10'),
                    "animation_12" => Settings::get('app_page_animation_12'),
                    "animation_18" => Settings::get('app_page_animation_18'),
                    "animation_20" => Settings::get('app_page_animation_20'),
                    "animation_21" => Settings::get('app_page_animation_21'),
                ];
                Cache::put('app_page_animation', json_encode($animation));
            }

            if(!Cache::has('app_emoji_cache') || !Cache::has('app_emoji_alt_str')){
                $flag = true;
                $page1 = Settings::get('app_emoji_page_1', []);
                $page2 = Settings::get('app_emoji_page_2', []);
                $page3 = Settings::get('app_emoji_page_3', []);
                $app_emoji_cache = [];
                $partern = '';
                $app_emoji_alt_str = '';
                if($page1){
                    foreach ($page1 as $emoji){
                        $key = _preg_prepare($emoji['alt']);
                        $app_emoji_cache[$emoji['alt']] = $emoji;
                        $app_emoji_alt_str .= '|'.$emoji['alt'];
                        if(_empty_($partern)){
                            $partern = '$'.$key.'';
                        }else{
                            $partern .= '|'.$key.'';
                        }
                    }
                }
                if($page2){
                    foreach ($page2 as $emoji){
                        $key = _preg_prepare($emoji['alt']);
                        $app_emoji_cache[$emoji['alt']] = $emoji;
                        $app_emoji_alt_str .= '|'.$emoji['alt'];
                        if(_empty_($partern)){
                            $partern = '$'.$key.'';
                        }else{
                            $partern .= '|'.$key.'';
                        }
                    }
                }
                if($page3){
                    foreach ($page3 as $emoji){
                        $key = _preg_prepare($emoji['alt']);
                        $app_emoji_cache[$emoji['alt']] = $emoji;
                        $app_emoji_alt_str .= '|'.$emoji['alt'];
                        if(_empty_($partern)){
                            $partern = '$'.$key.'';
                        }else{
                            $partern .= '|'.$key.'';
                        }
                    }
                }
                if($partern){
                    $partern .= '$';
                }
                $app_emoji_cache['partern'] = $partern;
                Cache::put('app_emoji_cache', json_encode($app_emoji_cache));
                Cache::put('app_emoji_alt_str', $app_emoji_alt_str);
            }


            if(!Cache::has('ad_config')) {
                $flag = true;
                global $__MINI_GLOBAL_TENANTS_ARR__;
                foreach ($__MINI_GLOBAL_TENANTS_ARR__ as $tennat_id){
                    $ad_config = [
                        'mp' => [
                            'position1' => [
                                "words" => Settings::get('ad_mp_words_sticky', [], true),
                                "single" => Settings::get('ad_mp_single_sticky', [], true),
                                "video" => Settings::get('ad_mp_video_sticky', [], true),
                            ],
                            'position2' => [
                                "flow" => Settings::get('ad_mp_push_flow', [], true),
                            ],
                            'position3' => [
                                'flow' => Settings::get('ad_mp_comment_push_flow', [], true),
                            ],
                            'position4' => [
                                'flow' => Settings::get('ad_mp_water_flow', [], true),
                            ],
                            'position5' => [
                                'reward' => Settings::get('ad_mp_reward_unit', ''),
                            ],
                            'position6' => [
                                'pre_sticker' => Settings::get('ad_mp_video_pre_sticker', ''),
                            ]
                        ],
                        'uni' => [
                            'position1' => [
                                "words" => Settings::get('ad_uni_words_sticky', [], true),
                                "single" => Settings::get('ad_uni_single_sticky', [], true),
                                "video" => Settings::get('ad_uni_video_sticky', [], true),
                            ],
                            'position2' => [
                                "flow" => Settings::get('ad_uni_push_flow', [], true),
                            ],
                            'position3' => [
                                'flow' => Settings::get('ad_uni_comment_push_flow', [], true),
                            ],
                            'position4' => [
                                'flow' => Settings::get('ad_uni_water_flow', true),
                            ],
                            'position5' => [
                                'reward' => Settings::get('ad_uni_reward_unit', '')
                            ],
                            'position6' => [
                                'pre_sticker' => null
                            ]
                        ]
                    ];
                    Cache::forget('ad_config' . '__'.$tennat_id);
                    Cache::put('ad_config' . '__'.$tennat_id, json_encode($ad_config));
                }
            }

            if(!Cache::has('yi_pay_config')) {
                $flag = true;
                $yi_pay_config = [
                    'app_id' => Settings::get('yi_app_id'),
                    'app_secret' => Settings::get('yi_app_secret'),
                    'provider_url'=> Settings::get('yi_provider_url'),
                    'site' => Settings::get('app_title'),
                    'notify_url' => env('APP_URL'). '/api/v1/app/yi/notify',
                    'return_url' => env('APP_URL')
                ];
                Cache::put('yi_pay_config', json_encode($yi_pay_config));
            }

            if(!Cache::has('app_pay_config')) {
                $flag = true;
                $app_pay_config = [
                    'alipay' => [
                        'default' => [
                            // 必填-支付宝分配的 app_id
                            'app_id' => Settings::get('ali_app_id'),
                            // 必填-应用私钥 字符串或路径
                            // 在 https://open.alipay.com/develop/manage 《应用详情->开发设置->接口加签方式》中设置
                            'app_secret_cert' => Settings::get('ali_private_key'),
                            // 必填-应用公钥证书 路径
                            // 设置应用私钥后，即可下载得到以下3个证书
                            'app_public_cert_path' => storage_path('app/certs/alipay/appCertPublicKey.crt'),
                            // 必填-支付宝公钥证书 路径
                            'alipay_public_cert_path' => storage_path('app/certs/alipay/alipayCertPublicKey_RSA2.crt'),
                            // 必填-支付宝根证书 路径
                            'alipay_root_cert_path' => storage_path('app/certs/alipay/alipayRootCert.crt'),
                            'return_url' => env('APP_URL'),
                            'notify_url' => env('APP_URL'). '/api/v1/app/ali/notify/app',
                            // 选填-第三方应用授权token
                            'app_auth_token' => '',
                            // 选填-服务商模式下的服务商 id，当 mode 为 Pay::MODE_SERVICE 时使用该参数
                            'service_provider_id' => '',
                            // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SANDBOX, MODE_SERVICE
                            'mode' => Pay::MODE_NORMAL,
                        ]
                    ],
                    'wechat' => [
                        'default' => [
                            // 必填-商户号，服务商模式下为服务商商户号
                            // 可在 https://pay.weixin.qq.com/ 账户中心->商户信息 查看
                            'mch_id' => Settings::get('mch_id'),
                            // 选填-v2商户私钥
                            'mch_secret_key_v2' => Settings::get('mch_secret'),
                            // 必填-v3 商户秘钥
                            // 即 API v3 密钥(32字节，形如md5值)，可在 账户中心->API安全 中设置
                            'mch_secret_key' => Settings::get('mch_secret'),
                            // 必填-商户私钥 字符串或路径
                            // 即 API证书 PRIVATE KEY，可在 账户中心->API安全->申请API证书 里获得
                            // 文件名形如：apiclient_key.pem
                            'mch_secret_cert' => storage_path('app/certs/wechat/apiclient_key.pem'),
                            // 必填-商户公钥证书路径
                            // 即 API证书 CERTIFICATE，可在 账户中心->API安全->申请API证书 里获得
                            // 文件名形如：apiclient_cert.pem
                            'mch_public_cert_path' => storage_path('app/certs/wechat/apiclient_cert.pem'),
                            // 必填-微信回调url
                            // 不能有参数，如?号，空格等，否则会无法正确回调
                            'notify_url' => env('APP_URL'). '/api/v1/app/wechat/notify',
                            // 选填-公众号 的 app_id
                            // 可在 mp.weixin.qq.com 设置与开发->基本配置->开发者ID(AppID) 查看
                            'mp_app_id' => Settings::get('mp_app_id'),
                            // 选填-小程序 的 app_id
                            'mini_app_id' => Settings::get('app_id'),
                            // 选填-app 的 app_id
                            'app_id' => Settings::get('app_app_id'),
                            // 选填-合单 app_id
                            'combine_app_id' => '',
                            // 选填-合单商户号
                            'combine_mch_id' => '',
                            // 选填-服务商模式下，子公众号 的 app_id
                            'sub_mp_app_id' => '',
                            // 选填-服务商模式下，子 app 的 app_id
                            'sub_app_id' => '',
                            // 选填-服务商模式下，子小程序 的 app_id
                            'sub_mini_app_id' => '',
                            // 选填-服务商模式下，子商户id
                            'sub_mch_id' => '',
                            // 选填-微信平台公钥证书路径, optional，强烈建议 php-fpm 模式下配置此参数
                            'wechat_public_cert_path' => [
//                        '45F59D4DABF31918AFCEC556D5D2C6E376675D57' => __DIR__.'/Cert/wechatPublicKey.crt',
                            ],
                            // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SERVICE
                            'mode' => Pay::MODE_NORMAL,
                        ]
                    ],
                    'unipay' => [
                        'default' => [
                            // 必填-商户号
                            'mch_id' => '777290058167151',
                            // 必填-商户公私钥
                            'mch_cert_path' => __DIR__.'/Cert/unipayAppCert.pfx',
                            // 必填-商户公私钥密码
                            'mch_cert_password' => '000000',
                            // 必填-银联公钥证书路径
                            'unipay_public_cert_path' => __DIR__.'/Cert/unipayCertPublicKey.cer',
                            // 必填
                            'return_url' => 'https://yansongda.cn/unipay/return',
                            // 必填
                            'notify_url' => 'https://yansongda.cn/unipay/notify',
                        ],
                    ],
                    'logger' => [
                        'enable' => true,
                        'file' => storage_path('logs/pay.log'),
                        'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                        'type' => 'daily', // optional, 可选 daily.
                        'max_file' => 5, // optional, 当 type 为 daily 时有效，默认 30 天
                    ],
                    'http' => [ // optional
                        'timeout' => 5.0,
                        'connect_timeout' => 5.0,
                        // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                    ],
                ];
                Cache::put('app_pay_config', json_encode($app_pay_config));

                $f1 = fopen(storage_path('app/certs/wechat/apiclient_key.pem'), 'w');
                fwrite($f1, Settings::get('mch_cert_key', ''));
                fclose($f1);

                $f2 = fopen(storage_path('app/certs/wechat/apiclient_cert.pem'), 'w');
                fwrite($f2, Settings::get('mch_cert_client', ''));
                fclose($f2);

                $f3 = fopen(storage_path('app/certs/alipay/appCertPublicKey.crt'), 'w');
                fwrite($f3, Settings::get('ali_my_publish_key', ''));
                fclose($f3);

                $f4 = fopen(storage_path('app/certs/alipay/alipayRootCert.crt'), 'w');
                fwrite($f4, Settings::get('ali_root_key', ''));
                fclose($f4);

                $f5 = fopen(storage_path('app/certs/alipay/alipayCertPublicKey_RSA2.crt'), 'w');
                fwrite($f5, Settings::get('ali_public_key', ''));
                fclose($f5);
            }

            if(!Cache::has('admin_color')) {
                $flag = true;
                $admin_color = [
                    '--color-primary' => Settings::get('--color-primary'),
                    '--color-secondary' => Settings::get('--color-secondary'),
                    '--primary-border-color' => Settings::get('--primary-border-color'),
                    '--secondary-border-color' => Settings::get('--secondary-border-color'),
                    '--color-success' => Settings::get('--color-success'),
                    '--color-danger' => Settings::get('--color-danger'),
                    '--color-warning' => Settings::get('--color-warning'),
                    '--color-info' => Settings::get('--color-info'),
                    '--color-light' => Settings::get('--color-light'),
                    '--color-grey' => Settings::get('--color-grey'),
                    '--color-dark' => Settings::get('--color-dark'),
                    '--color-muted' => Settings::get('--color-muted'),
                    '--color-white' =>  Settings::get('--color-white'),
                    '--mutted-border-color' => Settings::get('--mutted-border-color'),
                ];
                Cache::put('admin_color', json_encode($admin_color));
            }

            if(!Cache::has('admin_color')) {
                $flag = true;
                $foot_tool = Settings::get('sticky_list_foot_tool', '', true);
                $foot_tool_arr = explode('|', $foot_tool);
                $footer = [
                    'left' => [],
                    'right' => []
                ];
                if ($foot_tool_arr && count($foot_tool_arr) == 2) {
                    if ($foot_tool_arr[0]) {
                        for ($i = 0; $i < strlen($foot_tool_arr[0]); $i++) {
                            $footer['left'][] = (int)$foot_tool_arr[0][$i];
                        }
                    }
                    if ($foot_tool_arr[1]) {
                        for ($i = 0; $i < strlen($foot_tool_arr[1]); $i++) {
                            $footer['right'][] = (int)$foot_tool_arr[1][$i];
                        }
                    }
                    Cache::put(_multi_key('config:app:post:list:footer'), json_encode($footer));
                }
            }

            if(!Cache::has('img_all_style_names')) {
                $flag = true;
                $img_style_arr = Settings::get('img_style', []);
                if ($img_style_arr) {
                    $style_ = [];
                    foreach ($img_style_arr as $img_style) {
                        $style_ = array_merge($style_, explode(',', $img_style['style']));
                    }
                    Cache::put('img_all_style_names', json_encode(array_unique($style_)));
                }
            }

            if(!Cache::has('admin_played_users')) {
                $flag = true;
                $app_admin_super_admin = Settings::get('app_admin_super_admin');
                if ($app_admin_super_admin) {
                    global $__MINI_GLOBAL_TENANT_ID__;
                    if ($__MINI_GLOBAL_TENANT_ID__ > 0) {
                        foreach (explode(',', $app_admin_super_admin) as $user_id) {
                            if ($user_id > 0) {
                                update_user_meta($user_id, 'tenant_id_' . $__MINI_GLOBAL_TENANT_ID__, 1, 'n');
                            }
                        }
                    } else {
                        WxUser::whereIn('id', explode(',', $app_admin_super_admin))->update(['is_official' => 1]);
                    }
                }

                $app_admin_played_users = Settings::get('app_admin_played_users');
                if ($app_admin_played_users) {
                    $admin_played_users = WxUser::whereIn('id', explode(',', $app_admin_played_users))->get(['id', 'user_name', 'user_avatar']);
                    Cache::put(_multi_key('admin_played_users'), json_encode($admin_played_users));
                }
            }

            if(_empty_(env('APP_SUPER_ADMIN_USER_ID'))){
                $flag = true;
                _update_env([
                    'APP_SUPER_ADMIN_USER_ID' => Settings::get('app_admin_super_admin', ''),
                ], [], 1);
            }

            if($flag){
                SiteUtils::forget_config_data();

                $__global_config_version__ = Settings::get('__global_config_version__', 1) + 1;
                Settings::set('__global_config_version__', $__global_config_version__);
                GatewayUtils::success('all', 13, [ 'version' => $__global_config_version__, 'file' => basename(__FILE__) ]);
            }
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
        }
    }
}
